package com.mcdao.conf;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@RefreshScope
@MapperScan("com.mcdao.dao")
public class ServerConfiguration {

	@Value("${mysqldb.datasource.driverClass}")
	private String driverClass;

	@Value("${mysqldb.datasource.jdbcUrl}")
	private String jdbcUrl;

	@Value("${mysqldb.datasource.username}")
	private String username;

	@Value("${mysqldb.datasource.password}")
	private String password;

	@Value("${mysqldb.datasource.maxActive}")
	private Integer maxActive;

	@Value("${mysqldb.datasource.initialSize}")
	private Integer initialSize;

	@Value("${mysqldb.datasource.maxWaitMillis}")
	private Long maxWaitMillis;

	@Value("${mysqldb.datasource.minIdle}")
	private Integer minIdle;

	@Value("${mysqldb.datasource.removeAbandoned}")
	private boolean removeAbandoned;

	@Value("${mysqldb.datasource.removeAbandonedTimeout}")
	private Integer removeAbandonedTimeout;

	private final static String mapperLocations = "classpath*:com/mcdao/dao/*.xml";
	private final static String mabatisConf = "classpath:mybatis.xml";

	@Bean(destroyMethod = "close", initMethod = "init")
	@RefreshScope
	public DataSource dataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(driverClass);
		dataSource.setUrl(jdbcUrl);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		dataSource.setMaxActive(maxActive);
		dataSource.setInitialSize(initialSize);
		dataSource.setMaxWait(maxWaitMillis);
		dataSource.setMinIdle(minIdle);
		dataSource.setRemoveAbandoned(removeAbandoned);
		dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
		return dataSource;
	}
	
	@Bean
	public SqlSessionFactory sqlSessionFactory() throws Exception {
		SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		sqlSessionFactory.setDataSource(dataSource());
		sqlSessionFactory.setConfigLocation(resolver.getResource(mabatisConf));
		sqlSessionFactory.setMapperLocations(resolver.getResources(mapperLocations));
		return sqlSessionFactory.getObject();
	}
}
